// FileUriHandlerPlugin.kt
package com.sanji.capture_audio.plugin

import android.app.Activity
import android.content.Intent
import android.net.Uri
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry
import com.sanji.capture_audio.utils.FilePicker
import com.sanji.capture_audio.utils.Preferences
import android.util.Log

/**
 * 文件URI处理插件
 * 提供Flutter调用文件URI处理功能的能力
 */
class FilePickerPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
    // Flutter与原生通信的通道
    private var channel: MethodChannel? = null
    
    // 当前Activity引用
    private var activity: Activity? = null
    
    // 用于存储待处理的Flutter调用结果
    private var pendingResult: MethodChannel.Result? = null
    
    // 当前URI类型标识，用于区分不同用途的文件选择
    private var currentUriType: String? = null

    companion object {
        // 日志标签
        private const val TAG = "FilePickerPlugin"
        
        // 定义URI类型常量 - 开场白文件
        const val OPENING_STATEMENT = "opening_statement"
        // 录音文件夹
        const val RECORDING_FOLDER = "recording_folder"
        // TODO: 添加其他URI类型可以根据需要添加更多类型
    }
    
    /**
     * 当插件附加到Flutter引擎时调用
     * @param flutterPluginBinding Flutter插件绑定对象
     */
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "file_picker")
        channel?.setMethodCallHandler(this)
    }

    /**
     * 处理来自Flutter的方法调用
     * @param call 方法调用对象
     * @param result 方法调用结果回调
     */
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        // 检查activity是否可用
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity is not available", null)
            return
        }

        when (call.method) {
            "getFileUri" -> {
                pendingResult = result
                currentUriType = OPENING_STATEMENT
                FilePicker.getFileUri(activity!!)
                Log.d(TAG, "正在选择录音文件...")
            }
            "getFolderUri" -> {
                pendingResult = result
                currentUriType = RECORDING_FOLDER
                FilePicker.getFolderUri(activity!!)
                Log.d(TAG, "正在选择录音文件夹...")
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    /**
     * 当插件从Flutter引擎分离时调用
     * @param binding Flutter插件绑定对象
     */
    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel?.setMethodCallHandler(null)
    }

    /**
     * 当插件附加到Activity时调用
     * @param binding Activity插件绑定对象
     */
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    /**
     * 当Activity因配置更改而分离时调用
     */
    override fun onDetachedFromActivityForConfigChanges() {
        activity = null
    }

    /**
     * 当Activity重新附加时调用（配置更改后）
     * @param binding Activity插件绑定对象
     */
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    /**
     * 当插件从Activity分离时调用
     */
    override fun onDetachedFromActivity() {
        activity = null
    }

    /**
     * 处理Activity结果回调
     * @param requestCode 请求码
     * @param resultCode 结果码
     * @param data 返回数据
     * @return 是否处理了该结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (requestCode == FilePicker.REQUEST_CODE_SELECT_FILE || 
            requestCode == FilePicker.REQUEST_CODE_SELECT_FOLDER) {
            if (resultCode == Activity.RESULT_OK) {
                val uri = data?.data
                if (uri != null) {
                    // 根据类型保存URI到Preferences
                    if (activity != null && currentUriType != null) {
                        val preferences = Preferences(activity!!)
                        when (currentUriType) {
                            OPENING_STATEMENT -> {
                                preferences.openingStatement = uri
                                Log.d(TAG, "设置开场白文件: $uri")
                            }
                            RECORDING_FOLDER -> {
                                // 保存文件夹URI，实际录音文件将在该文件夹下创建
                                preferences.recordingOutputFile = uri
                                // 获取持久化权限 - 仅使用允许的标志位
                                try {
                                    val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or 
                                                  Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                    activity!!.contentResolver.takePersistableUriPermission(uri, takeFlags)
                                    Log.d(TAG, "设置录音文件夹并获取权限: $uri")
                                } catch (e: Exception) {
                                    Log.e(TAG, "获取URI权限失败: ${e.message}", e)
                                    pendingResult?.error("PERMISSION_ERROR", "获取文件夹权限失败: ${e.message}", null)
                                    pendingResult = null
                                    currentUriType = null
                                    return true
                                }
                                
                                // 验证是否真的获取到了权限
                                val persistedUriPermissions = activity!!.contentResolver.persistedUriPermissions
                                val hasPermission = persistedUriPermissions.any { it.uri == uri }
                                if (!hasPermission) {
                                    Log.e(TAG, "未能获取到文件夹的持久化权限: $uri")
                                    pendingResult?.error("PERMISSION_ERROR", "未能获取到文件夹的持久化权限", null)
                                    pendingResult = null
                                    currentUriType = null
                                    return true
                                }
                            }
                        }
                    }
                    
                    pendingResult?.success(uri.toString())
                    Log.d(TAG, "成功获取URI: $uri")
                } else {
                    pendingResult?.error("PICK_FILE_ERROR", "Failed to get URI", null)
                    Log.d(TAG, "获取URI失败")
                }
            } else {
                pendingResult?.error("PICK_FILE_CANCELLED", "Operation was cancelled", null)
                Log.d(TAG, "操作已取消")
            }
            pendingResult = null
            currentUriType = null  // 重置类型
            return true
        }
        return false
    }
}